/**
 * Copyright 2020-9999 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package su.transaction.service;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.extra.spring.SpringUtil;
import su.transaction.dao.ProductDao;


@Service
public class ProductService {
    @Autowired
    private ProductDao productDao;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateProductStockCountById(Integer stockCount, Long id){
        productDao.updateProductStockCountById(stockCount, id);
    }

    @Transactional
    public void updateProductPriceAndIncreaseProduct(String productName, Integer price){
        productDao.increaseProductPriceLikeName(productName, price);
        // 获取代理对象
        SpringUtil.getBean(ProductService.class).addProduct();
    }


    @Transactional
    public void updateProductPriceAndIncreaseProduct(Integer id, Integer price){
        productDao.increaseProductPriceByRangeId(id, price);
        // 获取代理对象
        SpringUtil.getBean(ProductService.class).addProduct();
    }

    /**
     * 新开一个事务，间隙锁
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addProduct() {
        productDao.addProduct(7L,"" + System.currentTimeMillis() + new Random().nextInt(1000),new Random().nextInt(1000),new Random().nextInt(1000) );

    }


    public static void main(String[] args) {

        try {
            int i = 1/0;
            test();
        }catch (Throwable e) {
            System.out.println("异常了");
        }
        System.out.println("ok");

    }

    public static void test() throws Throwable {
        throw new Exception("xx");
    }
}
